package ant.network;

import android.os.AsyncTask;
import ant.activity.AntActiviy;
import ant.io.LocationFile;
import ant.parser.Parsers;
import ant.tools.PrintOut;

/**
 * 异步请求数据类
 * 
 * @author 蒋豪
 * 
 */
public class AsyncRequest extends AsyncTask<Void, Void, Object> {

	private AntActiviy base;
	private RequestHelper dataOprate;

	public AsyncRequest(AntActiviy base, RequestHelper dataOprate) {
		this.base = base;
		this.dataOprate = dataOprate;
	}

	@Override
	protected Object doInBackground(Void... params) {
		RequestServer requestServer = new RequestServer();
		try {
			String string = null;
			/*判断请求方式*/
			if(ParameteInterface.REQUEST_POST==dataOprate.getRequestPattern()){
				string = requestServer.post(dataOprate);
			}else{
				string = requestServer.get(dataOprate);
			}
			/*判断是否需要写入缓存*/
			String fileName = dataOprate.getFileName();
			if(fileName!=null){
				LocationFile file=new LocationFile();
				file.writeCache(dataOprate.getPath(), fileName, string);
			}
			
			Parsers parserType = dataOprate.getParserType();
			return parserType.parseNetworkData(string, dataOprate);
		} catch (Exception e) {
			e.printStackTrace();
			PrintOut.error("Framework Exception",base.getClass().getName()+"请求数据时发生异常");
			return null;
		}
	}

	@Override
	protected void onPostExecute(Object result) {
		if(result==null){
			dataOprate.netFail(result);
		}else{
			dataOprate.complete(result);
		}
	}

}
